#!/usr/bin/perl
use strict;
use POSIX;

my $part = $ARGV[0];
my $outof = $ARGV[1];
my $tmpDir= $ARGV[2];

$|=1;

if($outof ==0) { $part =1; $outof = 1;}

my @files;
open(my $inFileList, "$tmpDir/tmp_filestoalign.txt") || die ("ERROR: Cannot file list of files to align: $tmpDir/tmp_filestoalign.txt");
while(<$inFileList>) {
	chomp;
	my ($filename,$anchorCNS)= split /,/;
	push @files, $filename;
}

if((scalar @files) ==0) { die "ERROR: Cannot file files to align\n"; }

my $numFiles = scalar @files;
my $start = floor(($numFiles / $outof) * ($part -1));
my $end = ceil(($numFiles/$outof) * ($part));
print "PROGRESS: Found " . $numFiles . " files. Processing $start to $end.\n";
my @filesToProcess = @files[$start..$end];
my $curPos=1;

foreach my $inFile (@filesToProcess) {
	#### build FASTA file for alignment
	if($inFile ne "" && -e $inFile) {
		my $outFile = $inFile;
		$outFile =~ s/\.fasta$/.aligned.fasta/;

		print "PROGRESS: (" . ($curPos++) . "/$numFiles) Aligning $inFile.\n";
		system("mafft --quiet --thread -1 --auto --ep 0.3 --op 7 $inFile > $outFile");
	}
}
